package cn.mes.service;

import cn.hutool.crypto.digest.DigestUtil;
import cn.mes.config.Message;
import cn.mes.dto.UserLoginDto;
import cn.mes.dto.UserRegisterDto;
import cn.mes.entity.User;
import cn.mes.mapper.UserMapper;
import cn.mes.service.impl.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class UserSericeImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Message login(UserLoginDto dto) {
        LambdaQueryWrapper<User> last = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, dto.getUsername())
                .last("limit 1");
        User user = userMapper.selectOne(last);
        String passworMd5 = DigestUtil.md5Hex(dto.getPassword());
        if (passworMd5.equals(user.getPassword())) {
            if (user.getRole() == 1) {
                return Message.login(-1, "登录成功", user.getUsername(), user.getId());
            } else {
                System.out.println(dto.getUsername() + "：登录成功");
                return Message.login(0, "登录成功,管理员", user.getUsername(), user.getId());
            }
        } else {
            return Message.login(1, "登录失败", null, null);
        }
    }

    @Override
    public Message register(UserRegisterDto dto) {
        LambdaQueryWrapper<User> last = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, dto.getUsername())
                .last("limit 1");
        User user = userMapper.selectOne(last);
        if (user != null) {
            return Message.error("该用户已经存在");
        }
        if (dto.getPassword().equals(dto.getConfirmPassword())) {
            User user1 = new User();
            user1.setId(String.valueOf(UUID.randomUUID()));
            user1.setUsername(dto.getUsername());
            user1.setPassword(DigestUtil.md5Hex(dto.getPassword()));
            user1.setCreateTime(new Date());
            user1.setIsDelete(0);
            user1.setRole(0);//普通用户
            userMapper.insert(user1);
            System.out.println(dto.getUsername() + "：注册成功");
            return Message.success("注册成功");
        } else {
            return Message.error("两次密码不一致");
        }
    }

}
